<?php
/**
 * Smart Library - Smart Framework
 * http://smart-framework.highet.eu
 *
 * @category   SmartL
 * @package    SmartL_DataBinder
 * @subpackage DataAdapter
 * @copyright  Copyright (c) 2005-2008 Smart Framework team - Stepan Sindelar, Vojtech Vit
 * @license    http://www.opensource.org/licenses/bsd-license.php	New BSD License
 */

/**
 * @see SmartL_DataBinder_DataAdapter_Abstract
 */
require_once 'SmartL/DataBinder/DataAdapter/Abstract.php';

/**
 * @package SmartL_DataBinder
 * @subpackage DataAdapter
 */
class SmartL_DataBinder_DataAdapter_ZendForm extends SmartL_DataBinder_DataAdapter_Abstract {
	/**
	 * @param mixed $name
	 * @param mixed $value
	 * @param Zend_Form $object
	 */
	protected function walk($name, $value = null, $object = null) {
		if ($object === null) {
			$object = $this->getObject ();
		}
		
		if (is_array ( $name )) {
			reset ( $name );
			$currentName = current ( $name );
			unset ( $name [key ( $name )] );
			if (count ( $name ) == 0) {
				return $this->walk ( $currentName, $value, $object );
			} else {
				$this->_checkElement ( $object, $currentName );
				return $this->walk ( $name, $value, $object->$currentName );
			}
		} elseif (is_string ( $name )) {
			$this->_checkElement ( $object, $name );
			if ($value !== null) {
				$object->$name->setValue ( $value );
			}
			return $object->$name->getValue ();
		} else {
			require_once 'SmartL/DataBinder/DataAdapter/ZendForm/Exception.php';
			throw new SmartL_DataBinder_DataAdapter_ZendForm_Exception ( "Adapter cannot recognize rule {$name}." );
		}
	}
	
	private function _checkElement(Zend_Form $form, $elementName) {
		if (! isset ( $form->$elementName )) {
			require_once 'SmartL/DataBinder/DataAdapter/ZendForm/Exception.php';
			throw new SmartL_DataBinder_DataAdapter_ZendForm_Exception ( "Form does not have element with {$elementName}" );
		}
	}
	
	public function set($name, $value) {
		$this->walk ( $name, $value );
	}
	
	public function get($name) {
		return $this->walk ( $name );
	}
}
